    //
//  TdkcURLManager.m
//  BaseTdkc
//
//  Created by DavidHuang on 16/7/7.
//  Copyright © 2016年 黄栋炜. All rights reserved.
//  单例

#import "TdkcURLManager.h"
#import "AFNetworking.h"
#import "MJExtension.h"
#import "YYReachability.h"
#import "SVProgressHUD.h"
#import "ConstantVariable.h"

//暂时的测试链接
#define kFeatureService_Target_URL  @"bali/FeatureServer"
#define kFeatureService_Dugui_URL  @"duogui/zh/MapServer"


#define kToJsonParams  @{@"f":@"pjson"}

#define kFolders  @"folders"
#define kService  @"services"
#define kLayers  @"layers"
#define kUrl @"url"
#define kId  @"id"


@interface TdkcURLManager ()
@property (nonatomic , copy) ReadUrlSuccessBlock internalReadUrl;
@property (nonatomic , copy) ServiceNameBlock internalSeviceNameExist;

@end

@implementation TdkcURLManager

+ (instancetype)sharedTdkcURLManager
{
    return [[self alloc] init];
}

static id _instace = nil;
+ (id)allocWithZone:(struct _NSZone *)zone
{
    if (_instace == nil) {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            _instace = [super allocWithZone:zone];
        });
    }
    return _instace;
}


- (id)init
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instace = [super init];
    });
    return _instace;
}


+ (id)copyWithZone:(struct _NSZone *)zone
{
    return _instace;
}

+ (id)mutableCopyWithZone:(struct _NSZone *)zone
{
    return _instace;
}

- (void)readURL:(ReadUrlSuccessBlock)readUrl {
    _internalReadUrl = readUrl;
    
    //直接读取 root 对象
    if(self.rootArr && self.rootArr.count > 0){
        _internalReadUrl(self.rootArr , YES);
        return;
    }else {
        [self.rootArr removeAllObjects];
    }
    
    
    //读取配置文件
    NSString *plistPath = [Utility documentPathWithSubDocumentName:kTdkcPlistName];
    BOOL ret =  [[NSFileManager defaultManager]fileExistsAtPath:plistPath];
    
    
    if (ret){
        self.rootArr = [NSMutableArray arrayWithContentsOfFile:plistPath];
        _internalReadUrl(self.rootArr,YES);
        return;

    }else {
        //从service 上下载 url 到配置文件中
        [self downLoadURLTdkcURLFromPlist];
    }
    
}

//下载 Url 地址
- (void)downLoadURLTdkcURLFromPlist {
    if(![YYReachability reachability].isReachable) {
        ZZXAlert(@"无法连接网络");
        return;
    }
    
    if(!self.targetServiceUrl) return;
    
    //请求所有目录下的文件 f=pjson
    if([KEY_BASE_URL isEqualToString:self.targetServiceUrl]){
        
        [[BaseRequest shareInstance]sendRequestType:RequestTypeGet Url:nil parameter:kToJsonParams success:^(NSDictionary *source) {
            self.folders = source[kFolders];
            self.services = [Services mj_objectArrayWithKeyValuesArray:source[kService]];
            [self requestMidStr];
        } fail:^(NSError *error) {
            
        }];
    }else { 
        NSString *keyStr = [self.targetServiceUrl substringFromIndex:KEY_BASE_URL.length];
        
        [[BaseRequest shareInstance]sendRequestType:RequestTypeGet Url:keyStr parameter:kToJsonParams success:^(NSDictionary *source) {
            self.folders = source[kFolders];
            self.services = [Services mj_objectArrayWithKeyValuesArray:source[kService]];
            [self requestMidStr];
        } fail:^(NSError *error) {
            
        }];
    }
  
}


- (void)requestMidStr {
    
    for (Services *service in self.services) {
        NSString *urlStr = [NSString stringWithFormat:@"%@/%@",service.name,service.type];
        
        //全部存进去
        NSString *processUrl = [NSString stringWithFormat:@"%@/%@",KEY_BASE_URL, urlStr];
        
        [self.rootArr addObject:processUrl];
    }
    
    NSString *plistPath = [Utility documentPathWithSubDocumentName:kTdkcPlistName];
    BOOL ret =  [[NSFileManager defaultManager]fileExistsAtPath:plistPath];
    
    if (!ret){
        BOOL ret = [self.rootArr writeToFile:plistPath atomically:YES];
        if (ret) {
            //重新下载的在这里传 rootArr
            _internalReadUrl(self.rootArr,YES);
            NSLog(@"write into file success");
        }else {
            _internalReadUrl(self.rootArr,NO);
            [SVProgressHUD showErrorWithStatus:@"下载资源文件失败"];
            NSLog(@"write into file fail");
        }
    }
}

- (BOOL)isTdkcUrlPlistExist {
    NSString *plistPath = [Utility documentPathWithSubDocumentName:kTdkcPlistName];
    BOOL ret = [[NSFileManager defaultManager]fileExistsAtPath:plistPath];
    
    //检测 tdkc.plist 文件的时候,同时将 tdkcFeature 的检测绑定
    //只在有文件的时候绑定
    if(ret){
        //因为 tdkc.plist 文件一旦加载,默认认为其 URL 与线上保持一致,若有更改,删除后,重新下载,所以可以本地读取
        if(self.rootArr && self.rootArr.count > 0){
        }else {
            [self.rootArr removeAllObjects];
            self.rootArr = [NSMutableArray arrayWithContentsOfFile:plistPath];
        }
        
        //可能包含多这个 featureService
        for (NSString *urlStr in self.rootArr) {
            
            NSString *typeName = [[urlStr componentsSeparatedByString:@"/"] lastObject];
            if([typeName.lowercaseString isEqualToString:kFeatureServiceTypeName]){
                self.tdkcFeatureServiceURLStr = urlStr;
                break;
            }else  if([typeName.lowercaseString isEqualToString:kMapServiceTypeName]){
                self.tdkcMapServiceURLStr = urlStr;
                break;
            }
        }
        
    }
    
    return  ret;
}

#pragma mark -- 检测服务的名称是否存在

- (void)checkServiceName:(NSString *)name isExist:(ServiceNameBlock)isSeviceNameExist  {
    _internalSeviceNameExist = isSeviceNameExist;
    if(self.nameArr.count > 0)
        [self.nameArr removeAllObjects];
    
    //请求所有目录下的文件 f=pjson
    
    [[BaseRequest shareInstance]sendRequestType:RequestTypeGet Url:nil parameter:kToJsonParams success:^(NSDictionary *source) {
        self.folders = source[kFolders];
        self.services = [Services mj_objectArrayWithKeyValuesArray:source[kService]];
        
        [self checkAndRestoreServiceNamesWithName:name];
    } fail:^(NSError *error) {
        
    }];
    
    //name ==
}
- (void)checkAndRestoreServiceNamesWithName:(NSString *)checkName{
    BOOL isInFolder = NO;
    BOOL isInService = NO;
    for (NSString *foldName in self.folders) {
        if ([checkName isEqualToString:foldName]) {
            isInFolder = YES;
        }
    }
    
    for (Services *service in self.services) {
        if ([checkName isEqualToString:service.name]) {
            isInFolder = YES;
        }
    }
    
    if (isInFolder && isInService) {
        ZZXAlert(@"资源文件名冲突");
    }
    if(isInFolder){
        
        //目标文件的 Url 默认只有两层
        self.targetServiceUrl  = [NSString stringWithFormat:@"%@/%@",KEY_BASE_URL,checkName];
        _internalSeviceNameExist(YES);
        return;
    }
    
    if(isInService && !isInFolder){
        //目标文件的 Url
         self.targetServiceUrl  = [NSString stringWithFormat:@"%@",KEY_BASE_URL];
        _internalSeviceNameExist(YES);
        return;
    }
    
    if(!isInFolder && !isInService){
        _internalSeviceNameExist(NO);
    }
    
}


-(NSMutableArray *)rootArr {
    if (_rootArr== nil) {
        self.rootArr = [NSMutableArray array];
    }
    return _rootArr;
}

- (NSMutableArray *)layers {
    if (_layers == nil) {
         self.layers = [[NSMutableArray alloc]init];
    }
    return _layers;
}
-  (NSMutableArray *)nameArr {
    if (_nameArr == nil) {
        self.nameArr = [[NSMutableArray alloc]init];
    }
    return _nameArr;
}

@end

@implementation Services
@end
@implementation Folders
@end

@implementation Layers
//+ (NSDictionary *)mj_replacedKeyFromPropertyName {
//    return @{@"ID" : @"id"};
//}
@end




